import 'package:flutter/cupertino.dart';

///使用时，要将该变量，在MaterialApp中的navigatorObservers注册
///MaterialApp(
///    navigatorObservers: [lifeObserver],
///    home: FirstWidget(),
///)
final RouteObserver<Route> lifeObserver = RouteObserver();

///用于 监听声明周期，onResume、onPause获取当前控件是否可见
abstract class LifeState<T extends StatefulWidget> extends State<T>
    with WidgetsBindingObserver, RouteAware {
  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    lifeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    var route = ModalRoute.of(context);
    if(route != null )lifeObserver.subscribe(this,route);
    super.didChangeDependencies();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if(state == AppLifecycleState.resumed){
      onResumed();
    }else if(state == AppLifecycleState.paused){
      onPaused();
    }
  }
  /// Called when the top route has been popped off, and the current route
  /// shows up.
  @override
  void didPopNext() { onResumed(); }

  /// Called when the current route has been pushed.
  @override
  void didPush() { onResumed(); }

  /// Called when the current route has been popped off.
  @override
  void didPop() { onPaused(); }

  /// Called when a new route has been pushed, and the current route is no
  /// longer visible.
  @override
  void didPushNext() { onPaused(); }

  void onResumed(){}
  void onPaused(){}
}
